//
//  GooOcr.m
//  iOcr
//
//  Created by Matri Ning on 1/18/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "GooOcr.h"

#import "GDataServiceGoogleDocs.h"
#import "GDataEntryContent.h"
#import "GDataEntryDocBase.h"
#import "GDataQueryDocs.h"
#import "FunOCRAppDelegate.h"

@implementation GooOcr

@synthesize delegate;
@synthesize mDocListFeed;
@synthesize uploadImage;
@synthesize ocrEntry;



- (id) init{
	
	
	[super init];
	
	appDelegate = (FunOCRAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	return self;
}





-(void)uploadImage:(UIImage *)imageFile AndName: (NSString *)docName{
	
		Class entryClass = NSClassFromString(@"GDataEntryStandardDoc");
		GDataEntryDocBase *newEntry =[entryClass documentEntry];
	    [newEntry setTitleWithString:docName];
			
		double compressionRatio=1.0;
		NSData *imageData=UIImageJPEGRepresentation(imageFile,compressionRatio);
		while ([imageData length]>500000) { 
			compressionRatio=compressionRatio*0.9;
			imageData=UIImageJPEGRepresentation(imageFile,compressionRatio);
		}
		
		[newEntry setUploadData:imageData];
		[newEntry setUploadMIMEType:@"image/jpeg"];
		[newEntry setUploadSlug:@"test"];
	
		
		
		NSURL *postURL = [NSURL URLWithString:@"http://docs.google.com/feeds/default/private/full?ocr=true"];
		//insert the entry into the docList feed
		GDataServiceTicket *ticket;
	
		GDataServiceGoogleDocs *docsService = [appDelegate docsService];
		ticket = [docsService fetchEntryByInsertingEntry:newEntry
										  forFeedURL:postURL
											delegate:self
								   didFinishSelector:@selector(uploadFileTicket:finishedWithEntry:error:)];
		
		[self setUploadTicket:ticket];
}





- (void)uploadFileTicket:(GDataServiceTicket *)ticket
	   finishedWithEntry:(GDataEntryDocBase *)entry
                   error:(NSError *)error {
	NSLog(@"file added");
	[self setUploadTicket:nil];
	if (entry) {
		
		[entry setETag:@"*"];
		
		NSLog(@"entry at GooOcr :: %@", [entry ETag]);
		appDelegate.currentEntry = entry;
		
		NSLog(@"appDelegate.currentEntry at GooOcr :: %@", [appDelegate.currentEntry ETag]);
		//ocrEntry=entry;
		
		NSLog(@"appDelegate.currentEntry at GooOcr :: %@", [[appDelegate.currentEntry content] stringValue]);
		[delegate serviceDidComplete];
	}
	else {
		
		[delegate serviceDidFailWithError];
	}
	
}




- (void)setUploadTicket:(GDataServiceTicket *)ticket {
	NSLog(@"haha");
	[mUploadTicket release];
	mUploadTicket = [ticket retain];
}






@end